/**
* @file executor_manager.cpp
*
* Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/

#include "executor_manager.h"
#include "mmpa/mmpa_api.h"
#include "log_inner.h"
#include "error_codes_inner.h"

namespace acl {
void ExecutorManager::AddExecutor(uint32_t &modelId, std::unique_ptr<gert::ModelV2Executor> executor)
{
    const std::lock_guard<std::mutex> locker(mutex_);
    ++modelIdGenerator_;
    modelId = modelIdGenerator_.load();
    executorMap_[modelId] = std::move(executor);
}

aclError ExecutorManager::DeleteExecutor(const uint32_t modelId)
{
    const std::lock_guard<std::mutex> locker(mutex_);
    const auto iter = executorMap_.find(modelId);
    if (iter == executorMap_.end()) {
        ACL_LOG_ERROR("model is not loaded, modelId is %u", modelId);
        return static_cast<aclError>(ACL_ERROR_GE_EXEC_MODEL_ID_INVALID);
    }
    (void)executorMap_.erase(iter);
    return ACL_SUCCESS;
}

void ExecutorManager::GetRuntimeV2Env()
{
    char_t enableRuntimeV2Flag[MMPA_MAX_PATH] = {};
    if (mmGetEnv("ENABLE_RUNTIME_V2", static_cast<char_t *>(enableRuntimeV2Flag),
        static_cast<uint32_t>(sizeof(enableRuntimeV2Flag))) == EN_OK) {
        ACL_LOG_INFO("runtime2.0 switch has been opened");
        enableRuntimeV2_ = true;
    }
}

std::shared_ptr<gert::ModelV2Executor> ExecutorManager::GetExecutor(const uint32_t modelId)
{
    const std::lock_guard<std::mutex> locker(mutex_);
    const auto iter = executorMap_.find(modelId);
    if (iter == executorMap_.end()) {
        return nullptr;
    }
    return iter->second;
}
}